package handler

import (
	"app/cache"
	"app/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	appName := c.PostForm("appName")
	appGo, _ := strconv.Atoi(c.PostForm("appGo"))
	typesId, _ := strconv.Atoi(c.PostForm("typesId"))
	username := c.PostForm("username")
	if appName == "" || appGo == 0 || typesId == 0 || username == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
	}
	data := model.App{
		//Model:    gorm.Model{},
		AppName:  appName,
		AppGo:    appGo,
		TypesId:  typesId,
		Username: username,
	}
	tx := model.DB.Begin()
	var err error
	defer func() {
		if r := recover(); r != nil {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "发布失败",
			})
			return
		}
	}()

	if err = tx.Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	err = tx.Commit().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	model.DB.Where("id=?", data.ID).Find(&model.App{})
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Create(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
}
func TypeList(c *gin.Context) {
	var app []model.App
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("apps").Joins("LEFT JOIN types ON apps.types_id = types.id").Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
}
func AppGo(c *gin.Context) {
	var app []model.App
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": app,
	})
}
func AddGos(c *gin.Context) {
	var app model.App
	model.DB.Where("id=?", app.ID).Find(&model.App{})
	redis_key := "list" + strconv.Itoa(int(app.ID))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
